#include "myprinter.h"
#include <QDebug>
#include <QDateTime>
#include <QThread>
#include <QtCore/QTextCodec> 

MyPrinter::MyPrinter(QObject *parent) : QObject(parent) 
{
    Printer_SerialPort = new QSerialPort;
}
MyPrinter::~MyPrinter()
{
    if (Printer_SerialPort->isOpen()) 
    { 
        Printer_SerialPort->close();
    }
    delete Printer_SerialPort;
}

bool MyPrinter::Printer_open(QString comName)
{
    if (Printer_SerialPort->isOpen()) 
    {
        Printer_SerialPort->close();
    }
    Printer_SerialPort->setPortName(comName);
    Printer_SerialPort->setBaudRate(QSerialPort::Baud9600);
    Printer_SerialPort->setDataBits(QSerialPort::Data8);
    Printer_SerialPort->setStopBits(QSerialPort::OneStop);
    Printer_SerialPort->setParity(QSerialPort::NoParity);
    if (Printer_SerialPort->open(QIODevice::ReadWrite))
    {
        return true;
    }
    else
    {
        qDebug()<<"printer ttyS1 open error!";
        return false;
    }
}
bool MyPrinter::Printer_close()
{
    if (Printer_SerialPort->isOpen()) 
    {
        Printer_SerialPort->close();
    }
    return true;
}

void MyPrinter::sendCommand(QByteArray cmd,int cmdLen)
{
    if(!printer_ok || !Printer_SerialPort->isOpen())
    {
        qDebug() << "Printer not ready: isOpen=" << Printer_SerialPort->isOpen();
        return;
    }
    Printer_SerialPort->write(cmd,cmdLen);
    Printer_SerialPort->flush();
    Printer_SerialPort->waitForBytesWritten(50);
}

// 配置汉字模式
void MyPrinter::Printer_set_hz()
{
    QByteArray cmd("\x1C\x26", 2);
    sendCommand(cmd,cmd.size());
}

// 取消汉字模式
void MyPrinter::Printer_cancel_hz()
{
    QByteArray cmd("\x1C\x2E", 2);
    sendCommand(cmd,cmd.size());
}

// 重置打印机
void MyPrinter::Printer_reset()
{
    QByteArray cmd("\x1B\x40", 2);
    sendCommand(cmd,cmd.size());
}

// 配置字符集1,包括 ASCII 字符,及各种图形符号等
void MyPrinter::Printer_set_charset1()
{
    QByteArray cmd("\x1B\x36", 2);
    sendCommand(cmd,cmd.size());
}
// 配置字符集2,包括德文法文俄文日语片假名等
void MyPrinter::Printer_set_charset2()
{
    QByteArray cmd("\x1B\x37", 2);
    sendCommand(cmd,cmd.size());
}
// 配置字体大小 fontSize取值：1~8
void MyPrinter::Printer_set_fontsize(unsigned char fontSize)
{
    if ((fontSize>8)||(fontSize<1))
    {
        qDebug()<<"fontSize error!";
        return;
    }
    unsigned char fscmd[8] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77};
    QByteArray cmd("\x1D\x21\x00", 3);
    cmd[2] = fscmd[fontSize-1];    
    sendCommand(cmd,cmd.size());
    return;
}

// 配置左限 leftlimit取值：0~255
void MyPrinter::Printer_set_leftlimit(unsigned char leftlimit)
{
    QByteArray cmd("\x1B\x6C\x00", 3);
    cmd[2] = leftlimit;    
    sendCommand(cmd,cmd.size());
}

// 配置右限 rightlimit取值：0~255
void MyPrinter::Printer_set_rightlimit(unsigned char rightlimit)
{
    QByteArray cmd("\x1B\x51\x00", 3);
    cmd[2] = rightlimit;    
    sendCommand(cmd,cmd.size());
}
// 配置左边距 用 nL 和 nH 设定左边空白量为(nL+nH*256)×0.125毫米。其中,0≤nL≤255,0≤nH≤1,0≤nL+nH*256≤384。
void MyPrinter::Printer_set_leftmargin(unsigned char nL,unsigned char nH)
{
    if ((nL+nH*256)>384||(nH>1))
    {
        qDebug()<<"leftmargin parameter error!";
        return;
    }
    QByteArray cmd("\x1D\x4C\x00\x00", 4);
    cmd[2] = nL;    
    cmd[3] = nH;    
    sendCommand(cmd,cmd.size());
}

// 配置右边距 用 nL 和 nH 设定右边空白量为(nL+nH*256)×0.125毫米。其中,0≤nL≤255,0≤nH≤1,0≤nL+nH*256≤384。
void MyPrinter::Printer_set_rightmargin(unsigned char nL,unsigned char nH)
{
    if ((nL+nH*256)>384||(nH>1))
    {
        qDebug()<<"rightmargin parameter error!";
        return;
    }
    QByteArray cmd("\x1D\x57\x00\x00", 4);
    cmd[2] = nL;    
    cmd[3] = nH;    
    sendCommand(cmd,cmd.size());
}

// 配置字间距 用nP设定字间距。其中,0≤nP≤255。
void MyPrinter::Printer_set_character_spacing(unsigned char nP)
{
    QByteArray cmd("\x1B\x70\x00", 3);
    cmd[2] = nP;    
    sendCommand(cmd,cmd.size());
}

// 配置行间距 用nP设定行间距为(nP*0.125 毫米),点阵图形打印时nP应为0，文本打印时推荐设置为3
void MyPrinter::Printer_set_line_spacing(unsigned char nP)
{
    QByteArray cmd("\x1B\x31\x00", 3);
    cmd[2] = nP;    
    sendCommand(cmd,cmd.size());
}
// 配置对齐方式 align取值：0~2 0:左对齐 1:居中对齐 2:右对齐
void MyPrinter::Printer_set_align(unsigned char align)
{
    if (align>2)
    {
        qDebug()<<"align parameter error!";
        return;
    }
    QByteArray cmd("\x1B\x61\x00", 3);
    cmd[2] = align;    
    sendCommand(cmd,cmd.size());
}

// 配置
bool MyPrinter::Printer_config()
{
    // 配置字符集1,包括 ASCII 字符,及各种图形符号等
    Printer_set_charset1();
    // 配置汉字模式
    Printer_set_hz();
    // 配置字体大小为1
    Printer_set_fontsize(1);
    return true;
}
// 初始化
bool MyPrinter::Printer_init(QString comName)
{
    printer_ok = false;
    // 初始化
    if(Printer_open(comName))
    {
        // 初始化成功，设置标志位
        printer_ok = true;
        Printer_print_off();
        Printer_close();
        return true;
    }
    else
    {
        return false;
    }
}
/********************************************************** 
 打印二维码 
 version:二维码版本，取值0~9 0:自动选择版本
 ecc:二维码纠错级别，取值0~3 依次对应 0:7%, 1:15%, 2:25%, 3:30%
 qrcode:二维码内容
 ***********************************************************/
void MyPrinter::Printer_print_qrcode(unsigned char version,unsigned char ecc,QByteArray qrcode)
{
    if ((version>9)||(ecc>3))
    {
        qDebug()<<"qrcode parameter error!";
        return;
    }
    if (qrcode.size() > 65533)
    {
        qDebug() << "QR code content too long (max 65533 bytes)!";
        return;
    }
    // 总长度为二维码内容长度+2字节
    int total_len = qrcode.size()+2;
    unsigned char ml,mh;
    ml = total_len%256;
    mh = total_len/256;
    QByteArray cmd("\x1D\x28\x31\x00\x00\x00\x00", 7);
    cmd[3] = ml;
    cmd[4] = mh;
    cmd[5] = version;
    cmd[6] = ecc;
    cmd.append(qrcode); 
    sendCommand(cmd,cmd.size());
}
// 打印走纸 nL为走纸行数
void MyPrinter::Printer_print_feed(unsigned char nL)
{
    QByteArray cmd("\x1B\x64\x00", 3);
    cmd[2] = nL;
    sendCommand(cmd,cmd.size());
}
// 关闭打印
void MyPrinter::Printer_print_off()
{
    QByteArray cmd("\x1D\x64\x00", 3);
    sendCommand(cmd,cmd.size());
}
// 打开打印
void MyPrinter::Printer_print_on()
{
    QByteArray cmd("\x1D\x64\x01", 3);
    sendCommand(cmd,cmd.size());
}
// 打印小票
bool MyPrinter::Printer_print_receipt(float weight,float unitprice,float totalprice)
{
    if (!printer_ok)
    {
        qDebug() << "Printer_print_weights error: Printer not initialized";
        return false;
    }
    if (!Printer_SerialPort->isOpen()) 
    {
        if(!Printer_SerialPort->open(QIODevice::ReadWrite))
        {
            qDebug() << "Printer_print_weights error: Printer not open";
            return false;
        }
    }
    //打开打印
    Printer_print_on();
    Printer_reset();
    // 设置
    Printer_config();
  
    // 打印走纸 8行
    Printer_print_feed(8);
    
    // 配置对齐方式 1:居中对齐
    Printer_set_align(1);

    // 打印开始标记
    QString StartLine = ">>> START <<<\n";
    QByteArray StartCmd = StartLine.toUtf8();
    sendCommand(StartCmd, StartCmd.size());

    // 打印走纸 1行
    Printer_print_feed(1);
    // 打印公司名称
    QString englishTitle = "Ubee furniture ltd .\n";
    QByteArray titleCmd = englishTitle.toUtf8();
    //QString chineseTitle = "约翰迪尔(天津)有限公司\n";
    //QByteArray titleCmd = QTextCodec::codecForName("GBK")->fromUnicode(chineseTitle);
    sendCommand(titleCmd, titleCmd.size());
    // 打印走纸 1行
    Printer_print_feed(1);
    // 打印日期时间
    QDateTime currentTime = QDateTime::currentDateTime();
    //QString timeFormat = "yyyy年MM月dd日 dddd HH:mm:ss"; // 中文格式（星期显示为"星期X"）
    QString timeFormat = "yyyy-MM-dd dddd HH:mm:ss";
    QString timeStr = currentTime.toString(timeFormat);
    // 追加换行符（打印机每行需以\n结尾）
    timeStr += "\n"; 
    //QByteArray timeCmd = QTextCodec::codecForName("GBK")->fromUnicode(timeStr);
    QByteArray timeCmd = timeStr.toUtf8();
    sendCommand(timeCmd, timeCmd.size());

    // 打印走纸 1行
    Printer_print_feed(1);

    // 配置对齐方式 0:左对齐
    Printer_set_align(0);
    // 打印重量
    QString totalsLine = QString::asprintf("weight: %.2f kg\n", weight);
    QByteArray totalsCmd = totalsLine.toUtf8();
    sendCommand(totalsCmd, totalsCmd.size());
    
    // 打印走纸 1行
    Printer_print_feed(1);

    // 打印单价
    QString unitpriceLine = QString::asprintf("unit price: %.2f\n", unitprice);
    QByteArray unitpriceCmd = unitpriceLine.toUtf8();
    sendCommand(unitpriceCmd, unitpriceCmd.size());
    // 打印走纸 1行
    Printer_print_feed(1);
    // 打印总价
    QString totalpriceLine = QString::asprintf("total price: %.2f\n", totalprice);
    QByteArray totalpriceCmd = totalpriceLine.toUtf8();
    sendCommand(totalpriceCmd, totalpriceCmd.size());
    // 打印走纸 1行
    Printer_print_feed(1);
    
    // 打印走纸 1行
    //Printer_print_feed(1);
    // 公司网址二维码
    //Printer_print_qrcode(0,0,"https://www.lascaux.com.cn/");
    // 打印走纸 1行
    //Printer_print_feed(1);
    // 公司网址
    //QString WebLine = "https://www.lascaux.com.cn/\n";
    //QByteArray WebCmd = WebLine.toUtf8();
    //sendCommand(WebCmd, WebCmd.size());
    // 配置对齐方式 1:居中对齐
    Printer_set_align(1);
    // 打印走纸 1行
    Printer_print_feed(1);
    QString EndLine = "*** END ***\n";
    QByteArray EndCmd = EndLine.toUtf8();
    sendCommand(EndCmd, EndCmd.size());
    // 打印走纸 8行
    Printer_print_feed(8);
    // 关闭打印
    Printer_print_off();
    Printer_SerialPort->close();
    return true;
}
